


const app = getApp();
//录音器
const manage = wx.getRecorderManager();
//播放器android
const innerAudioContext = wx.createInnerAudioContext();

//背景音乐播放器IOS
const backAudioManager = wx.getBackgroundAudioManager();

Page({

  data: {
    activityid: "",
    btnHide: false,
    maiHide: true,
    loadingHide: false,
    loadingText: "加载中",
    winHeight: wx.getSystemInfoSync().windowHeight + 30,
    recordTime: 0,
    pageNo: 1,
    hasNext: false,
    awardList: []
  },
  onLoad: function (res) {
    var that = this;
    //初始化数据设置
    //判断是否是从二维码进来的
    
    if (res.scene){
      that.setData({
        activityid: decodeURIComponent(res.scene)
      });
    }else{
      that.setData({
        activityid: res.activityid
        // activityid: "61201801250000267"
      });
    }
    console.log(that.data.activityid);
    // 0.加载获取红包详情
    this.getBonusDetail();

    // 1.登录
    if(!app.data.userid){
      wx.login({
        success: res => {
          //拥有授权码后，去获取userId
          app.getUserId(res.code, function () {
            //回调函数不做处理

            //finally.执行用户信息获取，并且回传后台保存。
            wx.getUserInfo({
              success: res => {
                app.globalData.userInfo = res.userInfo
                
                //存储用户信息
                app.storeUserInfo();
              }
            });
            

          });
        }
      });
    }
   

  },
  //转发按钮触发事件
  onShareAppMessage: function (res) {


    if (res.from === 'button') {
      // 来自页面内转发按钮

      //获取活动的id
      var activityId = res.target.dataset.activityid;
    }
    return {
      title: '自定义转发标题' + activityId,
      path: '/pages/index/index?id=' + activityId,
      success: function (res) {
        // 转发成功

 
      },
      fail: function (res) {
        // 转发失败
      
      }
    }
  },
  //获取红包详情
  getBonusDetail: function () {
    var that = this;
    var url = app.data.url + "getActivityDetail.do?activityId="+this.data.activityid;
    var dataForm = {
      "type": "my",
      "pageNo": that.data.pageNo
    };
    app.sendPost(url, dataForm, function (res) {
      that.setData({
        loadingHide: true
      });
    
      if(res.data){
        var data = res.data;
        var items = data.items;
        that.data.awardList = that.data.awardList.concat(items);
        that.setData({
          "word": data.word,
          "imgUrl": data.imgUrl,
          "totalAmount": data.amount,
          "wxName": data.wxName,
          "totalCount": data.totalCount,
          "usedCount": data.usedCount,
          "awardList": that.data.awardList,
          "grantNickName": data.wxName,
          loadingHide: true,
          hasNext: data.next
          
        });
      }

    });
  },
  //转发功能
  onShareAppMessage: function (res) {
 
    if (res.from === 'button') {
      // 来自页面内转发按钮
     
      
    }
    return {
      title: '说口令领红包',
      path: '/pages/bonus_detail/bonus_detail?activityid=' + that.data.activityid,
      success: function (res) {
        // 转发成功

       
      },
      fail: function (res) {
        // 转发失败
      
      }
    }
  },
  showRecord: function(){
    //显示麦克风图标
    var that = this;
    that.setData({
      maiHide: false
    });
  },
  //录音并且上传
  //开始录制音频
  startRecord: function () {
    var that = this;
    
    
    
    wx.getSetting({
      success: function (res) {
       
        if (res) {
          if (!res.authSetting['scope.record']) {
            console.log("录音权限不足");
            app.toSetAuth();
          } else if (!res.authSetting['scope.userInfo']) {
            console.log("用户信息权限不足");
            app.toSetAuth();
          } else {
            //保存一次用户信息
            //执行用户信息获取，并且回传后台保存。
            wx.getUserInfo({
              success: res => {
                app.globalData.userInfo = res.userInfo
                //存储用户信息
                app.storeUserInfo();
              }
            });

            //开始录音
            manage.start({
              format: 'mp3',
              sampleRate: 16000,
              numberOfChannels: 1,
              encodeBitRate: 96000,
              frameSize: 50
            });

            //开始事件
            manage.onStart(() => {
              console.log("开始事件");
              //计时器置零
              that.setData({
                recordTime: 1
              });
              //录音开始
              

              that.data.interval = setInterval(function () {
                that.data.recordTime += 1;
                console.log(that.data.recordTime);
                that.setData({
                  //格式化时间显示
                  recordTime: that.data.recordTime
                });
              }, 1000);
            });
 
          }
        }
      }
    });
    
    

    

    //开始录制
    // wx.startRecord({
    //   success: function (res) {
    //     console.log(res);
    //     var tempFilePath = res.tempFilePath;
    //     that.setData({
    //       tempFilePath: tempFilePath
    //     });
    //     //录制成功后，上传到服务器
    //     that.uploadRecordFile(tempFilePath);
    //   },
    //   fail: function () {
    //     console.log("失败");
    //     //一般是由于无权限引起的。
    //     //权限判断
    //     wx.getSetting({
    //       success: function (res) {
    //         console.log(res);
    //         if (res) {
    //           if (!res.authSetting['scope.record']) {
    //             console.log("录音权限不足");
    //             app.toSetAuth();
    //           } else if (!res.authSetting['scope.userInfo']) {
    //             console.log("用户信息权限不足");
    //             app.toSetAuth();
    //           } else {
              
    //           }
    //         }
    //       }
    //     });
    //   },
    //   complete: function (e) {
    //     console.log("complete");
    //   }
    // });


  },
  //松手时触发
  endRecord: function () {
    var that = this;
    
    that.setData({
      maiHide: true
    });
   
    manage.stop();
    manage.onStop((res) => {
      clearInterval(that.data.interval);
      console.log('停止录音', res.tempFilePath)
      that.setData({
         tempFilePath: res.tempFilePath
      });
     //录制成功后，上传到服务器
     that.uploadRecordFile(res.tempFilePath);
      
    })

    // setTimeout(function () {
    //   wx.stopRecord({
    //     fail: function (res) {
    //       //alert("停止失败");
    //     },
    //     success: function (res) {
    //       clearInterval(that.data.interval);
    //       var localId = res.localId;
    //     }
    //   });
    // }, 800);

  },
  //上传文件
  uploadRecordFile: function (filePath) {
    var that = this;
    that.setData({
      loadingHide: false,
      loadingText: "红包抢夺中"
    });
    var url = app.data.url + "getBonusForActivity.do";
    wx.uploadFile({
      url: url,
      filePath: filePath,　//待上传的文件地址
      name: 'mfile',
      formData: {
        "activityId": that.data.activityid,
        "userId": app.data.userid,
        "recordTime": that.data.recordTime
      }, // HTTP 请求中其他额外的 form data
      success: function (res) {
        that.setData({
          loadingHide: true
        });
        var data = JSON.parse(res.data);
        console.log(data);
        if(data){
          if (data.result == "100"){
            wx.showModal({
              title: '提示',
              content: "恭喜您得到奖金",
              success: function (res) {
                
                if (res.confirm) {
                  wx.redirectTo({
                    url: '/pages/bonus_detail/bonus_detail?activityid=' + that.data.activityid,
                  })
                  console.log('用户点击确定')
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            });
          }else{
            wx.showModal({
              title: '提示',
              content: data.message,
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            });
          }
        }
      },
      fail: function (res) {
        console.log("addfood fail", res);
      },
    });
  },
  //播放音频文件
  playVideo: function (res) {
    wx.showToast({
      title: '开始播放',
      duration: 500
    })
    console.log(res);
    var that = this;
    var url = app.data.url + "playVideo.do?bonusId="+res.currentTarget.dataset.bonusid;
    console.log(that.data.tempFilePath);
    //根据ID查询播放哪段音频（先下载保存在本地，然后播放）
    wx.downloadFile({
      type: 'mp3',
      url: url, //仅为示例，并非真实的资源
      success: function (res) {
        console.log(res.tempFilePath);
        // wx.playVoice({
        //   filePath: res.tempFilePath,
        //   success: function () {
        //     console.log("播放成功");
        //     // wx.showToast({
        //     //   title: '播放成功',
        //     //   duration: 500
        //     // })
        //   },
        //   fail: function (res) {

        //     console.log("播放失败:");
        //     console.log(res);
        //     wx.showToast({
        //       title: '播放失败',
        //       duration: 500
        //     })
        //   }
        // })

        var sysRes = wx.getSystemInfoSync();
        if (sysRes.platform == 'ios') {
          backAudioManager.title = "录音";
          backAudioManager.src = res.tempFilePath;
          backAudioManager.play();
        } else {
           innerAudioContext.onPlay(() => {
             console.log('开始播放')
          });
          innerAudioContext.onError((res) => {
            console.log(res.errMsg);
            console.log(res.errCode);
            wx.showToast({
              title: '播放失败',
              duration: 500
            })
          });
          innerAudioContext.src = res.tempFilePath;
          innerAudioContext.obeyMuteSwitch = false;
          innerAudioContext.play();
        }

    

        // wx.saveFile({
        //   tempFilePath: res.tempFilePath,
        //   success: function (res) {
        //     var savedFilePath = res.savedFilePath


        //   }
        // })
        // innerAudioContext.onPlay(() => {
        //   console.log('开始播放')
        // })
        // innerAudioContext.onError((res) => {
        //   console.log(res.errMsg);
        //   console.log(res.errCode);
        //   wx.showToast({
        //     title: '播放失败',
        //     duration: 500
        //   })
        // })
        // innerAudioContext.src = res.tempFilePath;
        // innerAudioContext.obeyMuteSwitch = false;
        // innerAudioContext.play();
        

      }
    })
  },
  //页面关闭时触发
  onUnload: function () {
    // 页面关闭
    var that = this;
    setTimeout(function () {
      wx.stopRecord({
        fail: function (res) {
          //alert("停止失败");
        },
        success: function (res) {
          console.log(res);
          var localId = res.localId;
        }
      });
    }, 800);
    clearInterval(that.data.interval);
  },
  //再发一个红包
  toGrantWord: function(){
    wx.switchTab({
      url: '/pages/index_create/index_create',
    })
  },
  //提示如何分享
  toShareTip: function(){
    
    this.shareImage();
    
  },
  //去提现
  towithdraw: function () {
    wx.navigateTo({
      url: '/pages/withdraw/withdraw',
    })
  },
  //分享图片（生成图片）
  shareImage: function () {
    var that = this;
    that.setData({
      loadingHide: false
    });
    var dataForm = {
      'userId': app.data.userid,
      'activityId': that.data.activityid
    };
    var url = app.data.url + "shareImage.do";
    app.sendPost(url, dataForm ,function(res){
      that.setData({
        loadingHide: true
      });
      if(res.result == "100"){
        wx.navigateTo({
          url: '/pages/forward/forward?activityid=' + that.data.activityid,
        })
      }else{
        app.showMessage("生成分享图片失败");
      }
    });

  },
  //上拉响应事件
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log("上拉加载中");
    var that = this;
    if (!that.data.hasNext) {
      return;
    }
    that.data.pageNo += 1;
    that.setData({
      pageNo: that.data.pageNo,
      loadingHide: false
    });
    that.getBonusDetail();
  },

})